package com.hzz.web.boss.patrol;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzz.api.patrol.IPatrolTaskService;
import com.hzz.dto.patrol.MapCordinatesDto;
import com.hzz.dto.patrol.PatrolStatDto;
import com.hzz.dto.patrol.PatrolTaskDto;
import com.hzz.dto.patrol.TaskLogDto;
import com.hzz.entity.patrol.TaskLog;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.RfUser2Bean;
import com.hzz.framework.annotation.auth.Logical;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.util.*;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "临时巡查任务")
@RestController
@Slf4j
public class PatrolTaskController extends BaseController {
    @Resource
    RestTemplate restTemplate;
    
    @Autowired
    IPatrolTaskService patrolTaskService;
    
    @Autowired
    WordUtils wordUtils;
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private final static String templateXls = "classpath:export/analysis_patrol_task.xls";
    
    private final static String patrolTaskLogXls = "classpath:export/patrol_task_log.xls";
    
    static final String acPrefix = "/boss/patrol/patrolTask/";
    
    @RequiresPermissions("patrolTask:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "page/{pageNum}")
    // @ApiOperation(value = "信息分页(未删除)")
    public Response page(@ModelAttribute PatrolTaskDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("page.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            result.data = PageUtil.copy(patrolTaskService.findDataIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTask:info")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
    // @ApiOperation(value = "信息详情")
    public Response info(@PathVariable("id") Long id) {
        log.info("info.........");
        Response result = new Response();
        try {
            PatrolTaskDto dto = new PatrolTaskDto();
            dto.setId(id);
            dto.setDelFlag(0);
            result.data = patrolTaskService.findDataById(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTask:del")
    @RequestMapping(method = RequestMethod.POST, value = acPrefix + "del/{id}")
    @ALogOperation(type = "删除", desc = "临时巡查任务-逻辑删除")
    // @ApiOperation(value = "逻辑删除")
    public Response del(@PathVariable("id") Long id) {
        log.info("del.........");
        Response result = new Response(0, "success");
        try {
            PatrolTaskDto dto = new PatrolTaskDto();
            dto.setId(id);
            result.message = patrolTaskService.deleteDataById(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions(value = {"patrolTask:add", "patrolTask:edit" }, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT }, value = acPrefix + "save")
    @RfUser2Bean
    @ALogOperation(type = "修改", desc = "临时巡查任务")
    // @ApiOperation(value = "信息保存")
    public Response save(@Validated @ModelAttribute PatrolTaskDto dto, BindingResult bindingResult) {
        log.info("save.........");
        Response result = new Response(0, "success");
        try {
            // if ("1".equals(request.getSession().getAttribute(acPrefix + "save." + dto.getToken()))) {
            // throw new RuntimeException("请不要重复提交!");
            // }
            if (bindingResult.hasErrors()) {
                String errorMsg = "";
                List<ObjectError> errorList = bindingResult.getAllErrors();
                for (ObjectError error : errorList) {
                    errorMsg += (error.getDefaultMessage()) + ";";
                }
                result = Response.error(errorMsg);
            } else {
                result = patrolTaskService.saveOrUpdateData(dto);
                // request.getSession().setAttribute(acPrefix + "save." + dto.getToken(), "1");
            }
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("completionStat:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "completionStat/page/{pageNum}")
    // @ApiOperation(value = "信息分页(未删除)")
    public Response completionStatistics(@ModelAttribute PatrolTaskDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("completionStatistics.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            result.data = PageUtil.copy(patrolTaskService.findCompletionStatistics(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTaskLog:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "patrolTaskLog/page/{pageNum}")
    // @ApiOperation(value = "信息分页(未删除)")
    public Response findPatrolTaskLog(@ModelAttribute PatrolTaskDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("findPatrolTaskLog.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            result.data = PageUtil.copy(patrolTaskService.findPatrolTaskLog(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTaskLog:detail")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "patrolTaskLog/detail")
    // @ApiOperation(value = "信息分页(未删除)")
    public Response findPatrolTaskLogDetailById(@ModelAttribute PatrolTaskDto dto) {
        log.info("findPatrolTaskLogDetailById.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(1);
            dto.setDelFlag(0);
            if (ObjectUtils.isEmpty(dto.getId())) {
                result = Response.error("任务id不能为空");
            } else {
                dto.setAreaIds(null);
                TaskLogDto data = (TaskLogDto) patrolTaskService.findPatrolTaskLog(dto).getList().get(0);
                String path = data.getPatrolTrack();
                List<MapCordinatesDto> array = JSONArray.parseArray(path, MapCordinatesDto.class);
                List<Map> bdCoordsMap = geoconv(array);
                List<MapCordinatesDto> bdArray = new ArrayList<>();
                // array.forEach(c -> {
                // bdArray.add(CoordinatesConvertUtil.bd_encrypt(c));
                // });
                if (bdCoordsMap != null) {
                    bdCoordsMap.forEach(map -> {
                        MapCordinatesDto cord = new MapCordinatesDto();
                        cord.setLng(new BigDecimal(map.get("x").toString()));
                        cord.setLat(new BigDecimal(map.get("y").toString()));
                        bdArray.add(cord);
                    });
                    data.setPatrolTrack(JSON.toJSONString(bdArray));
                }
                result.data = data;
            }
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTaskLogJunior:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "patrolTaskLogJunior/page/{pageNum}")
    // @ApiOperation(value = "信息分页(未删除)")
    public Response findPatrolTaskLogJunior(@ModelAttribute PatrolTaskDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("findPatrolTaskLogJunior.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            result.data = PageUtil.copy(patrolTaskService.findPatrolTaskLogJunior(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("patrolTaskLog:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "patrolTaskLog/export")
    public void exportPatrolTaskLog(@ModelAttribute PatrolTaskDto dto) {
        log.info("exportPatrolTaskLog.........");
        try {
            setResponseHeader(request, response, "河长日志_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            List<TaskLog> dataIsList = patrolTaskService.findPatrolTaskLogList(dto);
            // 创建模板的副本
            InputStream inputStream = FileUtil.getFileAsInputStream(patrolTaskLogXls);
            File temp = new File(System.getProperty("java.io.tmpdir"), "patrol_task_log_template_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            FileUtils.copyInputStreamToFile(inputStream, temp);
            // 表格s数据填充
            InputStream input = new FileInputStream(temp);
            HSSFWorkbook workBook = new HSSFWorkbook(input);
            Sheet sheet = workBook.getSheetAt(0);
            try {
                for (int i = 0; i < dataIsList.size(); i++) {
                    TaskLog data = dataIsList.get(i);
                    // 从第2行开始写
                    Row row = sheet.createRow(i + 1);
                    
                    row.createCell(0).setCellValue(StrUtil.asString(data.getRiverCourseName()));// 行政区划
                    row.createCell(1).setCellValue(StrUtil.asString(data.getAreaNames()));
                    row.createCell(2).setCellValue(StrUtil.asString(data.getExecutorRole()));
                    row.createCell(3).setCellValue(StrUtil.asString(data.getTaskContent()));
                    row.createCell(4).setCellValue(StrUtil.asString(data.getExecutorName()));
                    row.createCell(5).setCellValue(StrUtil.asString(data.getStatus()));
                    row.createCell(6).setCellValue(StrUtil.asString(sdf.format(data.getExcEndTime())));
                }
            } catch (Exception e) {
                log.error("excel数据导出填充异常!", e);
            }
            workBook.write(response.getOutputStream());
            workBook.close();
            input.close();
            FileUtil.closeStream(inputStream);
            temp.delete();
        } catch (Exception e) {
            log.error("excel数据导出异常", e);
            WebUtil.sendJson(response, Response.error(500, "excel数据导出异常!" + e.getMessage()));
        }
    }
    
    @RequiresPermissions("patrolTaskLogJunior:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "patrolTaskLogJunior/export")
    public void exportPatrolTaskLogJunior(@ModelAttribute PatrolTaskDto dto) {
        log.info("exportPatrolTaskLogJunior.........");
        try {
            setResponseHeader(request, response, "河长日志_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            List<TaskLog> dataIsList = patrolTaskService.findPatrolTaskLogListJunior(dto);
            // 创建模板的副本
            InputStream inputStream = FileUtil.getFileAsInputStream(patrolTaskLogXls);
            File temp = new File(System.getProperty("java.io.tmpdir"), "patrol_task_log_template_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            FileUtils.copyInputStreamToFile(inputStream, temp);
            // 表格s数据填充
            InputStream input = new FileInputStream(temp);
            HSSFWorkbook workBook = new HSSFWorkbook(input);
            Sheet sheet = workBook.getSheetAt(0);
            try {
                for (int i = 0; i < dataIsList.size(); i++) {
                    TaskLog data = dataIsList.get(i);
                    // 从第2行开始写
                    Row row = sheet.createRow(i + 1);
                    
                    row.createCell(0).setCellValue(StrUtil.asString(data.getRiverCourseName()));// 行政区划
                    row.createCell(1).setCellValue(StrUtil.asString(data.getAreaNames()));
                    row.createCell(2).setCellValue(StrUtil.asString(data.getExecutorRole()));
                    row.createCell(3).setCellValue(StrUtil.asString(data.getTaskContent()));
                    row.createCell(4).setCellValue(StrUtil.asString(data.getExecutorName()));
                    row.createCell(5).setCellValue(StrUtil.asString(data.getStatus()));
                    row.createCell(6).setCellValue(StrUtil.asString(sdf.format(data.getExcEndTime())));
                }
            } catch (Exception e) {
                log.error("excel数据导出填充异常!", e);
            }
            workBook.write(response.getOutputStream());
            workBook.close();
            input.close();
            FileUtil.closeStream(inputStream);
            temp.delete();
        } catch (Exception e) {
            log.error("excel数据导出异常", e);
            WebUtil.sendJson(response, Response.error(500, "excel数据导出异常!" + e.getMessage()));
        }
    }
    
    @RequiresPermissions("patrolTaskLog:del")
    @RequestMapping(method = RequestMethod.POST, value = acPrefix + "logDel/{id}")
    @ALogOperation(type = "删除", desc = "河长巡查日志-逻辑删除")
    // @ApiOperation(value = "逻辑删除")
    public Response logDel(@PathVariable("id") Long id) {
        log.info("del.........");
        Response result = new Response(0, "success");
        try {
            PatrolTaskDto dto = new PatrolTaskDto();
            dto.setId(id);
            dto.setLogDelFlag(1);
            result = patrolTaskService.saveOrUpdateData(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("analysis:patrol")
    @RequestMapping(method = {RequestMethod.POST }, value = acPrefix + "patrolStat/{pageNum}/{pageSize}")
    public Response patrolStat(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize, PatrolStatDto dto) {
        log.info("patrolStat.........");
        Response result = new Response(0, "success");
        try {
            dto.setPageNum(pageNum);
            dto.setPageSize(pageSize);
            result.setData(PageUtil.copy(patrolTaskService.patrolStatTable(dto)));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    @RequiresPermissions("analysis:patrol")
    @RequestMapping(method = {RequestMethod.POST }, value = acPrefix + "patrolStat")
    public Response patrolStat(PatrolStatDto dto) {
        log.info("patrolStat.........");
        Response result = new Response(0, "success");
        try {
            result.setData(patrolTaskService.patrolStat(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    /**
     * <p>
     * 河长统计 导出。
     */
    @RequiresPermissions("analysis:patrol:export:xls")
    @RequestMapping(method = {RequestMethod.POST }, value = acPrefix + "patrolStatExport/xls")
    // @ApiOperation(value = "行政区划河长数量导出")
    public void analysisPatrolTaskExport(@ModelAttribute PatrolStatDto dto) throws Exception {
        log.info("analysisPatrolTaskExport.........");
        try {
            setResponseHeader(request, response, "巡查统计_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            List<PatrolStatDto> dataIsList = patrolTaskService.patrolStat(dto);
            // 创建模板的副本
            InputStream inputStream = FileUtil.getFileAsInputStream(templateXls);
            File temp = new File(System.getProperty("java.io.tmpdir"), "analysis_patrol_task_template_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            FileUtils.copyInputStreamToFile(inputStream, temp);
            // 表格s数据填充
            InputStream input = new FileInputStream(temp);
            HSSFWorkbook workBook = new HSSFWorkbook(input);
            Sheet sheet = workBook.getSheetAt(0);
            try {
                for (int i = 0; i < dataIsList.size(); i++) {
                    PatrolStatDto data = dataIsList.get(i);
                    // 从第2行开始写
                    Row row = sheet.createRow(i + 1);
                    
                    row.createCell(0).setCellValue(StrUtil.asString(data.getAreaName()));// 行政区划
                    row.createCell(1).setCellValue(StrUtil.asString(data.getCount3w()));
                    row.createCell(2).setCellValue(StrUtil.asString(fmtRate(data.getCount3w(), data.getCount3()) + "%"));
                    row.createCell(3).setCellValue(StrUtil.asString(data.getCount4w()));
                    row.createCell(4).setCellValue(StrUtil.asString(fmtRate(data.getCount4w(), data.getCount4()) + "%"));
                    row.createCell(5).setCellValue(StrUtil.asString(data.getCount5w()));
                    row.createCell(6).setCellValue(StrUtil.asString(fmtRate(data.getCount5w(), data.getCount5()) + "%"));
                }
            } catch (Exception e) {
                log.error("excel数据导出填充异常!", e);
            }
            workBook.write(response.getOutputStream());
            workBook.close();
            input.close();
            FileUtil.closeStream(inputStream);
            temp.delete();
        } catch (Exception e) {
            log.error("excel数据导出异常", e);
            WebUtil.sendJson(response, Response.error(500, "excel数据导出异常!" + e.getMessage()));
        }
    }
    
    @RequiresPermissions("patrolTaskLog:download")
    @RequestMapping(method = RequestMethod.GET, value = acPrefix + "patrolTaskLog/download")
    // @ApiOperation(value = "河长日志下载")
    public void downloadLog2Word(@ModelAttribute PatrolTaskDto dto, @RequestParam("zoom") Integer zoom, HttpServletRequest request,
            HttpServletResponse response) {
        log.info("download.........");
        Response result = new Response(0, "success");
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(1);
            dto.setDelFlag(0);
            if (ObjectUtils.isEmpty(dto.getId())) {
                result = Response.error("任务id不能为空");
            } else {
                dto.setAreaIds(null);// 根据id查询不需要此参数
                TaskLogDto data = (TaskLogDto) patrolTaskService.findPatrolTaskLog(dto).getList().get(0);
                String path = data.getPatrolTrack();
                List<MapCordinatesDto> gdArray = JSONArray.parseArray(path, MapCordinatesDto.class);
                List<Map> bdCoordsMap = geoconv(gdArray);
                List<MapCordinatesDto> bdArray = new ArrayList<>();
                // array.forEach(c -> {
                // bdArray.add(CoordinatesConvertUtil.bd_encrypt(c));
                // });
                if (bdCoordsMap != null) {
                    bdCoordsMap.forEach(map -> {
                        MapCordinatesDto cord = new MapCordinatesDto();
                        cord.setLng(new BigDecimal(map.get("x").toString()));
                        cord.setLat(new BigDecimal(map.get("y").toString()));
                        bdArray.add(cord);
                    });
                    data.setPatrolTrack(JSON.toJSONString(bdArray));
                }
                JSONArray array = JSONArray.parseArray(data.getPatrolTrack());
                StringBuffer paths = new StringBuffer();
                String markers = "";// 116.297611,40.047363|116.307223,40.056379
                String center = "";// 116.297611,40.047363
                String bbox = "";// 116.5,40.1;116.55,40.15
                for (int i = 0; i < array.size(); i++) {
                    if (i == 0) {
                        markers = array.getJSONObject(i).getString("lng") + "," + array.getJSONObject(i).getString("lat") + "|";
                        BigDecimal lng = new BigDecimal(array.getJSONObject(i).getString("lng")).setScale(1, BigDecimal.ROUND_UP);
                        BigDecimal lat = new BigDecimal(array.getJSONObject(i).getString("lat")).setScale(1, BigDecimal.ROUND_UP);
                        bbox = lng.toString() + "," + lat;
                    }
                    if (i == array.size() - 1) {
                        markers += array.getJSONObject(i).getString("lng") + "," + array.getJSONObject(i).getString("lat");
                    }
                    if (i == array.size() / 2) {
                        center = array.getJSONObject(i).getString("lng") + "," + array.getJSONObject(i).getString("lat");
                        BigDecimal lng = new BigDecimal(array.getJSONObject(i).getString("lng")).setScale(1, BigDecimal.ROUND_UP);
                        BigDecimal lat = new BigDecimal(array.getJSONObject(i).getString("lat")).setScale(1, BigDecimal.ROUND_UP);
                        bbox += ";" + lng.toString() + "," + lat;
                    }
                    paths.append(array.getJSONObject(i).getString("lng")).append(",").append(array.getJSONObject(i).getString("lat")).append(";");
                }
                if (paths.toString().endsWith(";")) {
                    paths.substring(0, paths.length() - 1);
                }
                String fileName = "河长日志" + LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ".docx";
                if (zoom == null) {
                    zoom = 12;
                } else {
                    zoom = zoom - 1;
                }
                String pathUrl = "http://api.map.baidu.com/staticimage/v2?ak=keY5Bh4GNuG79iCNIGgSl31pXpmjjW50&width=800&height=400" + "&center=" + center
                        + "&bbox=" + bbox + "&markers=" + markers + "&paths=" + paths + "&zoom=" + zoom + "&pathStyles=0xFF0000,3,1";
                Map<String, Object> params = new HashMap<>();
                params.put("riverCourseName", data.getRiverCourseName() == null ? "" : data.getRiverCourseName());
                params.put("executorRole", data.getExecutorRole() == null ? "" : data.getExecutorRole());
                params.put("status", data.getStatus() == null ? "" : data.getStatus());
                params.put("startTime", data.getStartTime() == null ? "" : data.getStartTime());
                params.put("endTime", data.getEndTime() == null ? "" : data.getEndTime());
                params.put("taskContent", data.getTaskContent() == null ? "" : data.getTaskContent());
                params.put("patrolKilometer", data.getPatrolKilometer() == null ? "" : data.getPatrolKilometer());
                params.put("eventInfo", data.getEventInfo() == null ? "" : data.getEventInfo());
                // 上报图片
                List<String> picList = new ArrayList<>();
                String pics = data.getTreatmentPrePics();
                if (StringUtils.isNotBlank(pics)) {
                    for (String url : pics.split(",")) {
                        picList.add(image2Base64(url));
                    }
                }
                params.put("picList", picList);
                // // 轨迹图片
                params.put("pathPic", image2Base64(pathUrl));
                try {
                    wordUtils.exportMillCertificateWord(request, response, params, "河长日志", "patrol_task_log.ftl");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            log.error("download exception", e);
            result = Response.error(e.getMessage());
        }
    }
    
    /**
     * 查询前五名巡查率
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = acPrefix + "getInspectionRateDESC")
    public Response<HashMap> getInspectionRateDESC() {
        log.info("getInspectionRateDESC.........");
        Response result = new Response(0, "success");
        try {
            result.setData(patrolTaskService.getInspectionRateDESC());
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    /**
     * 查询后5名巡查率
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = acPrefix + "getInspectionRateASC")
    public Response<HashMap> getInspectionRateASC() {
        log.info("getInspectionRateDESC.........");
        Response result = new Response(0, "success");
        try {
            result.setData(patrolTaskService.getInspectionRateASC());
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
    
    /**
     * 图片转为base64
     * @param path
     * @return
     */
    public static String image2Base64(String path) throws IOException {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try {
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(data);
        return base64;
    }
    
    /**
     * 获取巡查率，保留两位小数
     * @param numw 完成次数
     * @param num 总次数
     */
    private String fmtRate(String numw, String num) {
        Integer n1 = Integer.valueOf(numw);
        Integer n2 = Integer.valueOf(num);
        if (n1 == 0) {
            return "0";
        }
        DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
        return df.format((float) n1 / n2);// 返回的是String类型
    }
    
    /**
     * 高德坐标批量转换百度坐标，一次最多一百个坐标
     * @return
     */
    private List<Map> geoconv(List<MapCordinatesDto> gdArray) {
        String url = "http://api.map.baidu.com/geoconv/v1/?from=3&to=5&ak=keY5Bh4GNuG79iCNIGgSl31pXpmjjW50&coords=";
        // 单次批量最多转换一百个坐标
        int onceMax = 100;
        int loop = gdArray.size() / onceMax;
        if (gdArray.size() % onceMax > 0) {
            loop += 1;
        }
        for (int i = 0; i < loop; i++) {
            StringBuffer coords = new StringBuffer();
            if (i != loop - 1) {
                for (int j = 0; j < onceMax; j++) {
                    MapCordinatesDto cord = gdArray.get(i * onceMax + j);
                    coords = coords.append(cord.getLng()).append(",").append(cord.getLat()).append(";");
                }
            } else {
                for (int j = i * onceMax; j < gdArray.size(); j++) {
                    MapCordinatesDto cord = gdArray.get(j);
                    coords = coords.append(cord.getLng()).append(",").append(cord.getLat()).append(";");
                }
            }
            String coordsParam = coords.toString().endsWith(";") ? coords.toString().substring(0, coords.length() - 1) : coords.toString();
            // 调用api转换
            ResponseEntity<String> res = restTemplate.getForEntity(url + coordsParam, String.class);
            JSONObject jsonObject = JSONObject.parseObject(res.getBody());
            List<Map> xy = JSON.parseArray(jsonObject.getString("result"), Map.class);
            // System.out.println(JSON.toJSONString(xy));
            return xy;
        }
        return null;
    }
}